use std::{env, process, fs, process::Command};

use winapi::um::processthreadsapi::GetCurrentProcessId;

use crate::error::{AppErr, ErrorConvert};

fn create_reset_script(app_path: &str, new_path: &str) -> String {
    let pid = unsafe { GetCurrentProcessId() };
    format!(
r#"@echo off
set appPID={}
set appPath={}
set newAppPath={}
taskkill /PID "%appPID%" /F
timeout /t 1 /nobreak
copy /Y "%newAppPath%" "%appPath%"
start "" "%appPath%"
"#,
        pid, app_path, new_path
    )
}

const NEW_PATH: &'static str = r#"E:\Rust\reset-app\tmp\reset-app.exe"#;

fn reset_app(new_path: &str) -> Result<(), AppErr> {
    let p = env::current_exe()?;
    let app_path = p.to_str().convert()?;
    fs::write("./update.bat", create_reset_script(app_path, new_path) )?;

    _ = Command::new("cmd")
        .args(&["/C", "update.bat"])
        .spawn()?;

    process::exit(0);
    
}

#[tauri::command]
pub async fn reset_self() -> Result<(), AppErr> {
    
    _ = reset_app(NEW_PATH);
    Ok(())
}
